package com.slink.fxfk.framework.util;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;

import com.slink.fxfk.framework.exception.FXFKException;

/**
 * 异常处理类
 * 
 * @author 新
 * 
 */
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {
	
	@Autowired
	private LocaleResolver localeResolver;

	@Autowired
	private MessageSource messageSource;

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		if (ex instanceof FXFKException) {
			FXFKException fxfkException = (FXFKException) ex;

			if (StringUtil.isNotBlank(fxfkException.getCode())) {
				String url = request.getRequestURI().replaceFirst(
						request.getContextPath(), "");
				ModelAndView mv = new ModelAndView();

				// html请求
				if (url.endsWith(".html")) {
					mv.setViewName("/common/tip");
					mv.addObject("success", false);
					mv.addObject("message", this.messageSource.getMessage(
							fxfkException.getCode(),
							(Object[]) fxfkException.getData(), null,
							this.localeResolver.resolveLocale(request)));
				} else if (url.endsWith(".json")) {
					try {
						PrintWriter writer = response.getWriter();
						response.setCharacterEncoding("UTF-8");
						response.setContentType("text/plain; charset=utf-8");
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("_code", fxfkException.getCode());
						map.put("_message", this.messageSource.getMessage(
								fxfkException.getCode(),
								(Object[]) fxfkException.getData(), null,
								this.localeResolver.resolveLocale(request)));
						writer.write(new ObjectMapper().writeValueAsString(map));
						writer.flush();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				return mv;
			}
		}

		return null;
	}
}
